'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import request from '@/utils/request';
import React, { useCallback, useEffect, useState, Suspense } from 'react';
import PagesItem from '@/components/admin/pages/PagesItem';
import message from '@/components/common/message';
import { useSearchParams, useRouter } from 'next/navigation';
import { ROUTE_PAGES } from '@/config/settings';
import { debounce } from 'lodash';
import Pagination from '@/components/admin/common/Pagination';

function PagesContent() {
  const [loaded, setLoaded] = useState(false);
  const [pages, setPages] = useState([]);
  const [limit, setLimit] = useState(16);
  const [offset, setOffset] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const pageParam = searchParams.get('page');
    if (!pageParam) {
      const params = new URLSearchParams(searchParams);
      params.set('page', '1');
      router.replace(`?${params.toString()}`);
    } else {
      const pageNum = parseInt(pageParam, 10);
      setCurrentPage(isNaN(pageNum) || pageNum < 1 ? 1 : pageNum);
    }
  }, [searchParams, router]);

  useEffect(() => {
    setOffset((currentPage - 1) * limit);
  }, [currentPage, limit]);

  const fetchPages = useCallback(async () => {
    setLoaded(false);
    try {
      const res = await request(`/api/admin/pages?limit=${limit}&offset=${offset}`, { method: 'GET' });
      setPages(res.data);
      setTotalCount(res.count);
      setLoaded(true);
    } catch (error) {
      console.error('Failed to fetch pages:', error);
      message.error('加载页面失败，请稍后再试');
      setLoaded(true);
    }
  }, [limit, offset]);

  useEffect(() => {
    fetchPages();
    return () => setLoaded(false);
  }, [fetchPages]);

  const editHandle = (id) => {
    if (!id) {
      message.error('页面 ID 不存在');
      return;
    }
    router.push(`${ROUTE_PAGES}/${id}`);
  };

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const handleAddPage = useCallback(debounce(() => {
    message.success('页面创建中，请稍候...');
    fetch('/api/admin/pages', {
      method: 'POST',
      body: JSON.stringify({ status: 1, title: '新页面', content: '' })
    })
      .then(response => response.json())
      .then(data => {
        if (data.code === 0) {
          message.success('页面创建成功，请编辑内容...');
          router.push(`${ROUTE_PAGES}/${data.data.id}`);
        } else {
          message.error(data.codeMap[data.code]);
        }
      })
      .catch(error => {
        console.error('Error creating page:', error);
        message.error('创建页面失败，请稍后再试');
      });
  }, 100), [message, router]);

  const handlePageChange = (newPage) => {
    setCurrentPage(newPage);
    const params = new URLSearchParams(searchParams);
    params.set('page', newPage.toString());
    router.push(`?${params.toString()}`);
  };

  const handleCopy = (e, slug) => {
    e.stopPropagation();
    if (!slug) {
      message.error('当前Slug未配置，不能生成链接');
      return;
    }
    navigator.clipboard.writeText(`/pages/${slug}`).then(() => {
      message.success('页面链接已复制到剪贴板');
    }).catch(err => {
      console.error('Failed to copy:', err);
      message.error('复制链接失败，请手动复制');
    });
  }

  const handleDelete = async (e, id) => {
    e.stopPropagation();
    if (!window.confirm('确定要删除该页面吗？')) return;
    if (!id) {
      message.error('页面 ID 不存在');
      return;
    }
    try {
      const res = await request(`/api/admin/pages/${id}`, { method: 'DELETE' });
      if (res.code === 0) {
        message.success('页面删除成功');
        fetchPages();
      } else {
        message.error(res.codeMap[res.code]);
      }
    }
    catch (error) {
      console.error('Failed to delete page:', error);
      message.error('删除页面失败，请稍后再试');
    }
  }

  const handleSend = (e, slug, status) => {
    e.stopPropagation();
    if (status !== 0) {
      message.error('当前页面未启用，页面无法打开');
      return;
    }
    if (!slug) {
      message.error('当前Slug未配置，不能生成链接');
      return;
    } else {
      window.open(`${window ? window.origin : process.env.NEXT_PUBLIC_BASE_URL}/pages/${slug}`, '_blank', 'noopener,noreferrer');
    }
  }

  const content = (
    <div className='editor'>
      <PageTitle color='#FFFFFF' ader title="页面管理" buttonText={"添加页面"} onButtonClick={handleAddPage} />
      <div>
        <div className='grid grid-cols-4 gap-4 p-4 items-center bg-white sticky top-12 z-1 rounded-t-xs border-b border-gray-200 text-[#333333] text-xs font-semibold'>
          <div>标题</div>
          <div>状态</div>
          <div>创建时间</div>
          <div className='text-right pr-6'>功能配置</div>
        </div>
        <div className='bg-white rounded-b-sm'>
          {
            pages.length > 0 ? (
              pages.map(item => (<PagesItem value={item} key={item.id} onEdit={editHandle} onCopy={handleCopy} onDelete={handleDelete} onSend={handleSend}/>))
            ) : <div className="text-center">暂无数据</div>
          }
        </div>
        <Pagination total={totalCount} page={currentPage} limit={limit} leftDisabled={offset === 0} rightDisabled={offset + limit >= totalCount} leftOnClick={() => handlePageChange(Number(currentPage) - 1)} rightOnClick={() => handlePageChange(Number(currentPage) + 1)} onChange={handlePageChange} />
      </div>
    </div>
  );

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  );
}

export default function Pages() {
  return (
    <Suspense fallback={<div>加载中...</div>}>
      <PagesContent />
    </Suspense>
  );
}